<template>
  <el-dialog
    :title="title"
    :visible.sync="visible"
    :before-close="closeDialog"
    :close-on-click-modal="false"
    width="50%"
    top="5vh"
  >
    <el-form
      ref="createOrEditForm"
      v-loading="loading"
      label-position="right"
      label-width="100px"
      :model="form"
      :rules="formRules"
    >
      <el-form-item :label="$t('BookStore2[\'TemplateName\']')" prop="name">
        <el-input v-model="form.name" />
      </el-form-item>
      <el-form-item :label="$t('BookStore2[\'Display:Remark\']')" prop="remark">
        <el-input v-model="form.remark" type="textarea" />
      </el-form-item>
      <el-form-item :label="$t('BookStore2[\'TemplateBlobName\']')" prop="template.blobName">
        <el-upload
          accept=".doc, .docx"
          :action="action"
          :file-list="fileList"
          :on-success="handleSuccess"
          :on-remove="handleRemove"
          :before-upload="handleBeforeUpload"
        >
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">{{ $t('BookStore2[\'UploadAccept\']', ['doc/docx']) }}</div>
        </el-upload>
      </el-form-item>

      <!-- 隐藏表单 -->
      <el-form-item prop="id" hidden>
        <el-input v-model="form.id" />
      </el-form-item>
      <el-form-item prop="concurrencyStamp" hidden>
        <el-input v-model="form.concurrencyStamp" />
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="closeDialog">{{ $t('BookStore2[\'Cancel\']') }}</el-button>
      <el-button type="primary" @click="submitForm">
        <i class="el-icon-check" />
        {{ $t('BookStore2[\'Save\']') }}
      </el-button>
    </span>
  </el-dialog>
</template>

<script>
import {
  getById,
  create,
  edit
} from '@/api/messageTemplate/messageTemplate'
import store from '@/store'
export default {
  props: {
    context: {
      type: Object,
      required: true
    },
    visible: {
      type: Boolean,
      required: true,
      default: false
    }
  },
  data() {
    return {
      title: '',
      actionMode: '',
      loading: false,
      dataDict: {},
      form: {
        id: '',
        name: '',
        remark: '',
        template: {
          blobContainerName: '',
          blobName: '',
          fileName: ''
        },
        concurrencyStamp: ''
      },
      formRules: {
        name: [{ required: true, message: this.$t('BookStore2[\'ThisFieldIsRequired\']'), trigger: 'blur' }],
        'template.blobName': [{ required: true, message: this.$t('BookStore2[\'TemplateFileRequired\']'), trigger: 'blur' }]
      },
      action: process.env.VUE_APP_BLOB_UPLOAD,
      fileList: [],
      headers: {}
    }
  },
  watch: {
    context(newVal, oldVal) {
      this.loading = true
      this.title = newVal.title
      this.actionMode = newVal.actionMode
      this.$nextTick(function() {
        if (this.actionMode === 'edit') {
          /* 编辑模式 */
          if (newVal.id) {
            getById(newVal.id).then(resp => {
              if (resp) {
                this.form.id = resp.id
                this.form.concurrencyStamp = resp.concurrencyStamp
                this.form.name = resp.name
                this.form.remark = resp.remark
                if (resp.template) {
                  this.form.template.blobContainerName = resp.template.blobContainerName
                  this.form.template.blobName = resp.template.blobName
                  this.form.template.fileName = resp.template.fileName
                }
                this.refreshUpload(this.form.template.fileName)
              }
              this.loading = false
            })
          }
        } else {
          /* 创建模式 */
          this.loading = false
        }
      })
    }
  },
  async created() {
    if (store.getters.token) {
      this.headers['authorization'] = 'Bearer ' + store.getters.token
    }
    if (store.getters.tenant) {
      this.headers['__tenant'] = store.getters.tenant
    }
  },
  methods: {
    submitForm() {
      this.$refs.createOrEditForm.validate(async(isValid, invalidFields) => {
        if (isValid) {
          if (this.actionMode === 'edit') {
            await edit(this.form.id, this.form)
          } else {
            await create(this.form)
          }
          this.$message({ message: this.$t('BookStore2[\'Ok\']'), type: 'success' })
          this.closeDialog()
          this.$emit('saveSucceed')
        }
      })
    },
    handleSuccess(response, file, fileList) {
      this.form.template.blobContainerName = response.blobContainerName
      this.form.template.blobName = response.blobName
      this.form.template.fileName = response.fileName
      this.refreshUpload(response.fileName)
    },
    handleRemove(file, fileList) {
      this.removeTemplateFile()
    },
    handleBeforeUpload(file) {
      const ext = file.name.substring(file.name.lastIndexOf('.') + 1)
      if (ext !== 'doc' && ext !== 'docx') {
        this.$message({ message: this.$t('BookStore2[\'UploadAccept\']', ['doc/docx']), type: 'error' })
        return false
      }
    },
    removeTemplateFile() {
      this.form.template.blobContainerName = ''
      this.form.template.blobName = ''
      this.form.template.fileName = ''
    },
    refreshUpload(name) {
      this.fileList = [{ name: name }]
    },
    closeDialog() {
      this.resetDialog() // 重置表单
      this.$emit('update:visible', false)
    },
    resetDialog() {
      this.$refs.createOrEditForm.resetFields()
      this.fileList = []
    }
  }
}
</script>

<style scoped>
</style>
